package com.iot.dw.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.DoubleAccumulator;

@Slf4j
public class GbxfEncoder extends MessageToByteEncoder<GbxfMessage> {
    public GbxfEncoder() {
    }
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, GbxfMessage message, ByteBuf out) throws Exception {
        if(!message.isSuccess()){
            return;
        }
        out.writeByte(0x40);
        out.writeByte(0x40);
        out.writeByte(message.getSeqno()%256);
        out.writeByte(message.getSeqno()/256);
        out.writeByte(message.getVerl());
        out.writeByte(message.getVerh());

        var d= LocalDateTime.now();
        out.writeByte(d.getSecond() );
        out.writeByte(d.getMinute() );
        out.writeByte(d.getHour() );
        out.writeByte(d.getDayOfMonth() );
        out.writeByte(d.getMonthValue() );
        out.writeByte(d.getYear()-2000 );

        out.writerIndex(24);
        out.writeByte(message.getDataLen()%256);
        out.writeByte(message.getDataLen()/256);

        out.writeByte(message.getCmd() );
        var jym=GbxfDecoder.getCheckCode(out,2,25+message.getDataLen() );
        out.writeByte(jym);
        out.writeByte(0x23);
        out.writeByte(0x23);
        var hexStr=ByteBufUtil.hexDump(out,0,out.readableBytes() );
        log.info("发送 IP:{} id:{} Send:{} ",
                channelHandlerContext.channel().remoteAddress(),
                message.getId(),
                hexStr );
    }
}
